package top.lshaci.learning.springboot.mybatisplus.util;

import org.springframework.transaction.support.TransactionSynchronizationAdapter;
import org.springframework.transaction.support.TransactionSynchronizationManager;

/**
 * TransactionUtil
 *
 * @author lshaci
 * @version 1.0.3
 * @since 1.0.3
 */
public class TransactionUtil {

    static ThreadLocal<Integer> order = new ThreadLocal<>();

    public static void beforeCommit(Runnable command) {
        Integer order = getOrder();
        TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
            @Override
            public int getOrder() {
                return order;
            }

            @Override
            public void beforeCommit(boolean readOnly) {
                TransactionUtil.order.remove();
                command.run();
            }
        });
    }

    public static void afterCommit(Runnable command) {
        Integer order = getOrder();
        TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {

            @Override
            public int getOrder() {
                return order;
            }

            @Override
            public void afterCommit() {
                command.run();
            }
        });
    }

    private static Integer getOrder() {
        Integer currentOrder = TransactionUtil.order.get();
        TransactionUtil.order.set(currentOrder == null ? 0 : currentOrder + 1);
        return TransactionUtil.order.get();
    }
}
